import React, { Component } from 'react';
import ListLoading from 'atComponents/ListLoading';
import initAboutOrganizationOrProject from 'utils/initNavigation/initAboutOrganizationOrProject';
import { pages } from './interface';
import NewbieTask from 'components/newbieTask';
import utils from 'utils';
import { getPathWithNoRootPath } from 'utils/router';
import { getIntroPointState, setIntroPointState } from 'api';
import { Message } from '@teamix/ui';
import track from 'utils/track';
import intl from '../../../locale';

const { organization_id } = window.FORCE.organization;
const { id } = window.FORCE.user;
let searchOneRank = true;

export default class RootRouter extends Component {
  state = {
    activePage: null,
    newbieGuideVisible: false,
    newbieTaskFinished: true,
  };

  UNSAFE_componentWillMount() {
    if (organization_id !== '5f7051259cffa29cfdd39e47') {
      this.checkFinishNewbieTask();
    }
  }

  UNSAFE_componentWillReceiveProps(props) {
    const { newbieTaskFinished } = this.state;
    if (this.isHomePage(props.pageInfo, this.props.location)) {
      if (!newbieTaskFinished) {
        this.setState({
          newbieGuideVisible: true,
        });
      }
    } else {
      this.setState({
        newbieGuideVisible: false,
      });
    }
  }

  componentDidMount() {
    // 页面初始化时，调用一次 renderNewPage
    // this.renderNewPage(this.props.location.pathname);
    // 页面首次进入调用一次。切换路由不会调用，而是会触发componentDidUpdate
    this.props.getProjectTabInfo();
    this.renderNewPageDetail();
  }

  // 源文件内部之间的切换
  getIsProjectFile = (pathname) => {
    const { pathResource } = window.FORCE;
    const { fullPath = '' } = pathResource;
    if (!pathname.startsWith(`/${fullPath}`)) {
      return false;
    }
    const str = pathname.replace(`/${fullPath}`, '');
    return (
      str === '' ||
      str.startsWith('/tree') ||
      str.startsWith('/blob') ||
      str.startsWith('/new') ||
      str.startsWith('/edit')
    );
  };

  getIsRepoSetting = (pathname) => {
    const { pathResource } = window.FORCE;
    const { fullPath = '' } = pathResource;
    if (!pathname.startsWith(`/${fullPath}/settings`)) {
      return false;
    }
    const str = pathname.replace(`/${fullPath}/settings`, '');
    const settingPaths = [
      '',
      '/',
      '/branches',
      '/push_rules',
      '/merge_requests',
      '/webhooks',
      '/deploykeys',
      '/services',
      '/lfs',
    ];
    return settingPaths.includes(str);
  };

  getIsSecuritySwitchToTab = (pathname, prevPathname) => {
    const { pathResource } = window.FORCE;
    const { fullPath = '' } = pathResource;
    const str = prevPathname.replace(`/${fullPath}/project_security`, '');
    const indexPath = ['', '/'];
    return indexPath.includes(str) && pathname.startsWith(`/${fullPath}/project_security`);
  };

  getIsMr = (pathname) => {
    const { pathResource, codeReviewDetail } = window.FORCE;
    const { fullPath = '' } = pathResource;
    if (
      !codeReviewDetail ||
      !codeReviewDetail.id ||
      !pathname.startsWith(`/${fullPath}/merge_request/${codeReviewDetail.id}`)
    ) {
      return false;
    }
    const str = pathname.replace(`/${fullPath}/merge_request/${codeReviewDetail.id}`, '');
    const mrPaths = ['', '/', '/commits', '/changes'];
    return mrPaths.includes(str);
  };

  componentDidUpdate(prevProps) {
    // pathname 发生变化时，调用 renderNewPage
    const { pathname: pathnameWithRootpath, state } = this.props.location;
    const pathname = getPathWithNoRootPath(pathnameWithRootpath);
    const prevPathname = getPathWithNoRootPath(prevProps.location.pathname);

    if (pathname !== prevPathname) {
      // 如果是首页之间的变化则不请求
      const indexPathnames = [
        '/',
        '/groups',
        '/merge_requests',
        '/risk_control',
        '/audit',
        '/settings/repository_permissions',
        '/settings/group_permissions',
        '/settings/customize',
        '/settings/security',
        '/settings/security_notify',
        '/settings/admins',
      ];

      const isProjectFile = this.getIsProjectFile(pathname) && this.getIsProjectFile(prevPathname);
      const isRepoSetting = this.getIsRepoSetting(pathname) && this.getIsRepoSetting(prevPathname);
      // MR概览、历史、文件之间切换不请求
      const isMr = this.getIsMr(pathname) && this.getIsMr(prevPathname);
      // 从库安全首页切换到详情tab
      const isSecuritySwitchToTab = this.getIsSecuritySwitchToTab(pathname, prevPathname);
      const notneedReq =
        (indexPathnames.includes(pathname) && indexPathnames.includes(prevPathname)) ||
        isProjectFile ||
        isRepoSetting ||
        isSecuritySwitchToTab ||
        isMr;

        if (!(state && state.forceUpdate) && notneedReq) {
        if (isProjectFile) {
          const { pathResource } = window.FORCE;
          const { fullPath = '' } = pathResource;
          const curPathStr = pathname.replace(`/${fullPath}/`, '');
          if (!curPathStr || curPathStr === `/${fullPath}`) {
            this.renderNewPage(pathname, { forceUpdate: true });

            return;
          }
          const [subject, , ...filepathArr] = curPathStr.split('/');
          this.props.updateSetSelectedType({
            resourceSubject: {
              subject: subject || '',
              path: decodeURIComponent(filepathArr.join('/')) || '',
            },
          });
        }
        return;
      }
      this.renderNewPage(pathname, this.props.location.state);
    }

    // 视图在企业、企业设置、库间变化时，重新执行吊顶初始化
    // 从库内切到企业
    const fromProjectToOrganization =
      this.props.pageInfo.assetsName === 'organization' &&
      prevProps.pageInfo.assetsName !== 'organization';
    // 从企业首页切到企业设置
    const fromOrganizationToSettings =
      this.props.location.pathname.indexOf('/settings/') === 0 &&
      prevProps.location.pathname.indexOf('/settings/') !== 0;
    // 从企业设置切到企业首页
    const fromSettingsToOrganization =
      this.props.location.pathname.indexOf('/settings/') !== 0 &&
      prevProps.location.pathname.indexOf('/settings/') === 0;
    // 从非库切到库
    const fromOthersToProject =
      prevProps.pageInfo.assetsName &&
      this.props.pageInfo.assetsName &&
      prevProps.pageInfo.assetsName.indexOf('project') !== 0 &&
      this.props.pageInfo.assetsName.indexOf('project') === 0;
    // 从非组切到组
    const fromOthersToGroup =
      prevProps.pageInfo.assetsName &&
      this.props.pageInfo.assetsName &&
      prevProps.pageInfo.assetsName.indexOf('group') !== 0 &&
      this.props.pageInfo.assetsName.indexOf('group') === 0;
    // fullPath发生变化，为组、库间切换
    const fullPathChanged =
      prevProps.pageInfo.pathResource.fullPath &&
      this.props.pageInfo.pathResource.fullPath &&
      prevProps.pageInfo.pathResource.fullPath !== this.props.pageInfo.pathResource.fullPath;

    const pageSearchState =
      this.props.pageInfo.assetsName &&
      this.props.pageInfo.assetsName.indexOf('search') === 0 &&
      searchOneRank;
    if (fromProjectToOrganization || fromOrganizationToSettings || fromSettingsToOrganization) {
      this.setNavForOrganization();
    } else if (fromOthersToProject || fromOthersToGroup || fullPathChanged || pageSearchState) {
      searchOneRank = false;
      this.setNavForProject();
    }

    // 从非error到error，导航重置成首页的样子
    const fromOthersToError =
      prevProps.pageInfo.assetsName &&
      this.props.pageInfo.assetsName &&
      prevProps.pageInfo.assetsName !== 'error' &&
      this.props.pageInfo.assetsName === 'error';
    if (fromOthersToError) {
      this.setNavForOrganization();
    }

    // 需要重载
    if (this.props.reloading === true && prevProps.reloading === false) {
      this.setState(
        {
          activePage: <ListLoading />,
        },

        () => {
          const { assetsName, title } = this.props.pageInfo;
          let LoadablePage;
          if (assetsName.indexOf('project') === 0) {
            LoadablePage = pages.project;
          } else if (assetsName.indexOf('group') === 0) {
            LoadablePage = pages.group;
          } else {
            LoadablePage = pages[assetsName];
          }

          this.setState({
            activePage: <LoadablePage />,
          });

          document.title = title;

          this.props.reloadEnd();
        },
      );
    }
  }

  setNavForOrganization = () => {
    // FIXME 不先设成false的话，从企业-设置回首页有bug
    window.TB_NAVIGATION.setHomePageFlag(false);

    window.TB_NAVIGATION.setHomePageFlag(true);
    initAboutOrganizationOrProject();
  };

  setNavForProject = () => {
    window.TB_NAVIGATION.setHomePageFlag(false);
    initAboutOrganizationOrProject();
  };

  renderNewPage = (pathname, locationState) => {
    // this.setState({
    //   activePage: <ListLoading />,
    // });

    this.props.fetchPageInfo(pathname, locationState, () => {
      if (locationState && locationState.toastWarning) {
        Message.warning({
          title: locationState.toastWarning,
        });
        delete this.props.location.state.toastWarning;
      }
      this.renderNewPageDetail();
    });
  };

  renderNewPageDetail = () => {
    const { assetsName, title, pathResource } = this.props.pageInfo;

    let LoadablePage;
    if (assetsName.indexOf('project') === 0) {
      LoadablePage = pages.project;
    } else if (assetsName.indexOf('group') === 0) {
      LoadablePage = pages.group;
    } else if (assetsName.indexOf('search') === 0) {
      LoadablePage = pages.search;
    } else if (assetsName.indexOf('oauth') === 0) {
      LoadablePage = pages.oauth;
    } else {
      LoadablePage = pages[assetsName];
    }

    if (assetsName.indexOf('project') === 0 || assetsName.indexOf('group') === 0) {
      // 组内和库内的布局一样，都叫 project-container 了
      const isTooLarge = utils.isTooLarge(pathResource);
      // document
      //   .getElementById('container')
      //   .setAttribute(
      //     'class',
      //     'project-container',
      //   );

      if (assetsName.indexOf('project') === 0 && isTooLarge) {
        document.getElementById('container').classList.add('has-too-large-tip');
      }
      // 在mr页面，滚动区域不再是container,进行样式修改
      if (assetsName === 'projectMergeRequestDetail') {
        document.getElementById('container').classList.add('mr-container');
      }
    }

    this.setState({
      activePage: <LoadablePage />,
    });

    if (assetsName === 'error') {
      document.title = intl.get({
        id: 'code-assets.index.containers.router.AnErrorOccurredYunxiaoCodeup',
        defaultMessage: '出错啦 · 云效 Codeup',
      });
    }

    if (title) {
      document.title = title;
    }
  };

  checkFinishNewbieTask() {
    getIntroPointState('rdc_newbie_task')
      .then((result) => {
        if (result.state) {
          this.startNewbieTask();
          this.props.updateNewbieTaskStatus(result.result);
        } else {
          const newbieTaskFrom = utils.getUrlSearchParam('nb_from');
          if (newbieTaskFrom === 'console') {
            // 从控制台来的用户，打开新手任务
            this.startNewbieTask();
          } else if (newbieTaskFrom === 'laboratory') {
            // 从实验室来的，也打开新手任务
            this.startNewbieTask();
          } else {
            // 完成任务
            this.props.updateNewbieTaskExpandStatus(false);
            this.props.updateNewbieTaskStatus(result.result);
          }
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  startNewbieTask() {
    track({
      action: 'enter newbie task',
      page: 'home page',
      type: '',
      control: 'newbie task',
    });

    this.clearLocalStorage();
    const expand = window.localStorage.getItem('codeup-newbie-task-expand');
    if (expand !== undefined) {
      this.props.updateNewbieTaskExpandStatus(JSON.parse(expand));
    }
    this.setState({
      newbieTaskFinished: false,
    });

    if (this.isHomePage(this.props.pageInfo, this.props.location)) {
      this.setState({
        newbieGuideVisible: true,
      });
    }
  }

  isHomePage(pageInfo, location) {
    const { pathname } = location;
    if (pageInfo.assetsName) {
      if (pageInfo.assetsName === 'organization' && pathname && !pathname.startsWith('/settings')) {
        return true;
      }
    }
    return false;
  }

  onFinishNewbieTask(type) {
    this.setState(
      {
        newbieTaskFinished: true,
      },
      () => {
        setIntroPointState('rdc_newbie_task', {
          rdc_newbie_task_status: type,
        })
          .then(() => {
            if (type === 'finish') {
              Message.success({
                title: (
                  <span
                    dangerouslySetInnerHTML={{
                      __html: intl.get({
                        id: 'code-assets.index.containers.router.CongratulationsAllTasksHaveBeen',
                        defaultMessage: '恭喜&#127881，所有任务已完成',
                      }),
                    }}
                  />
                ),
              });
              setTimeout(() => {
                this.props.updateNewbieTaskStatus(type);
              }, 5000);
            } else {
              this.props.updateNewbieTaskStatus(type);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      },
    );
  }

  clearLocalStorage() {
    const { localStorage } = window;
    const taskRecord = localStorage.getItem('codeup-newbie-task-org_and_user');
    if (!taskRecord || taskRecord !== `${organization_id}-${id}`) {
      localStorage.removeItem('codeup-newbie-task-number');
      localStorage.removeItem('codeup-newbie-task-card-list');
      localStorage.removeItem('codeup-newbie-task-add_repository');
      localStorage.removeItem('codeup-newbie-task-expand');
      localStorage.setItem('codeup-newbie-task-org_and_user', `${organization_id}-${id}`);
    }
  }

  render() {
    // FIXME 新手任务相关代码待改版时需完全删除
    const { activePage, newbieGuideVisible } = this.state;
    // const { hasPush } = this.props.project.projectFiles;
    // const { welcomeDialogStatus } = this.props.organization.projects;

    // const mainPageCreateSuccess = this.props.organization.projects.createRepositorySuccess;
    // const demoProjectToastCreate = this.props.project.root.createRepositorySuccess;
    // const groupProjectCreate = this.props.group.groupHome.createRepositorySuccess;
    // const { closeImportRepository } = this.props.organization.projects;
    // const createRepoSuccess = mainPageCreateSuccess || demoProjectToastCreate || groupProjectCreate;

    // const isInHomePage = window.location.pathname === '/';
    // const showTask = isInHomePage ? welcomeDialogStatus === false : true;

    return (
      <React.Fragment>
        {activePage}
        {newbieGuideVisible && (
          <NewbieTask
            // pushCommit={hasPush}
            onChangeNewbieTaskVisible={(v) => {
              this.setState({
                newbieGuideVisible: v,
              });
            }}
            // createRepository={createRepoSuccess}
            // importRepository={closeImportRepository}
            onAllTasksFinished={() => {
              this.onFinishNewbieTask('finish');
              const { localStorage } = window;
              localStorage.removeItem(`codeup-newbie-task-invite-${organization_id}-status`);
              localStorage.removeItem(`codeup-newbie-task-invite-${organization_id}-current`);
            }}
            onCloseNewbieTask={() => {
              this.onFinishNewbieTask('close');
            }}
            onExpandStatusChange={(status) => {
              this.props.updateNewbieTaskExpandStatus(status);
            }}
            // welcomeDialogStatus={welcomeDialogStatus}
          />
        )}
      </React.Fragment>
    );
  }
}
